<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>localStorage</h1>
  <button id="save">save</button>
  <button id="get">get</button>
  <button id="remove">remove</button>
  <button id="clear">clear</button>

  <script>
    const btn = document.getElementById('save');
    btn.addEventListener('click', () => {
      const obj = {
        name: 'John',
        age: 30,
        sex: 'male',
        city: 'New York'
      }
      // localStorage.setItem('user', obj); //这样会变成普通字符串
      localStorage.setItem('user', JSON.stringify(obj)); // 转成JSON字符串会让对象按原样保留
    });

    const btn2 = document.getElementById('get');
    btn2.addEventListener('click', () => {
      const user = localStorage.getItem('user');// 读取本地存储的某条数据
      // console.log(user);
      console.log(JSON.parse(user));
    });

    const btn3 = document.getElementById('remove');
    btn3.addEventListener('click', () => {
      localStorage.removeItem('user');// 删除本地存储的某条数据
    });

    const btn4 = document.getElementById('clear');
    btn4.addEventListener('click', () => {
      localStorage.clear();// 清空本地存储的所有数据
    });
  </script>
</body>
</html>